//
//  APPSelectListAlertViewControl.swift
//  APP
//
//  Created by LXF on 2018/1/8.
//  Copyright © 2018年 Rdxer. All rights reserved.
//

import Foundation
import XXAutoLayout

public protocol APPSelectListAlertViewController_ItemModel: NSObjectProtocol {
    var alert_isSelected: Bool? { get set }
    var alert_title: String? { get }
    var multiple_select: Bool? { get }
    var canDelete: Bool? { get }
}
public extension APPSelectListAlertViewController_ItemModel{
    var canDelete: Bool? { return false }
}

public protocol APPSelectListAlertViewController_GroupModel: NSObjectProtocol {
    var alert_title: String? { get }
    var multiple_select: Bool? { get }
    var alert_itemModelList: [APPSelectListAlertViewController_ItemModel] { get set }
}

public class APPSelectListAlertViewController_GroupModelImpl: NSObject, APPSelectListAlertViewController_GroupModel {
    
    public var multiple_select: Bool?
    
    public var alert_title: String?
    public var alert_itemModelList: [APPSelectListAlertViewController_ItemModel]

    
    
    public init(title: String?, items: [APPSelectListAlertViewController_ItemModel],multiple_select:Bool = false) {
        alert_title = title
        alert_itemModelList = items
        self.multiple_select = multiple_select
    }
}

public class APPSelectListAlertViewController: APPCustomViewAlertViewController {
    
    public class Appearance{
        
        // check-selected
        public var cellIcon_Multiple_UnSelect = "xxappalert_check_unchecked_Multiple".xx_toImage(from: APPSelectListAlertViewController.self)
        // check-unselected
        public var cellIcon_Multiple_Select = "xxappalert_check-selected".xx_toImage(from: APPSelectListAlertViewController.self)
        
        public var cellIcon_Single_UnSelect = "xxappalert_check_unchecked".xx_toImage(from: APPSelectListAlertViewController.self)
        public var cellIcon_Single_Select = "xxappalert_check_checked".xx_toImage(from: APPSelectListAlertViewController.self)
    }
    
    
    public var isGlobalSingle = false
    
    public var appearance = Appearance.init()
    

    /// 获取选择了的 扁平化
    public func getSelectItemList() -> [APPSelectListAlertViewController_ItemModel] {
        var selectList: [APPSelectListAlertViewController_ItemModel] = []

        groupList.forEach { _, group in
            group.alert_itemModelList.forEach({ _, item in
                if item.alert_isSelected ?? false {
                    selectList.append(item)
                }
            })
        }

        return selectList
    }

    public var groupList: [APPSelectListAlertViewController_GroupModel]
    public func dataList(_ index: Int) -> [APPSelectListAlertViewController_ItemModel] { return groupList[index].alert_itemModelList }
    public func data(_ indexPath: IndexPath) -> APPSelectListAlertViewController_ItemModel { return dataList(indexPath.section)[indexPath.row] }

    public var tableView: UITableView

    public var configCell: ((_ cell: APPSelectListAlertCell, _ model: APPSelectListAlertViewController_ItemModel) -> Void)?

    public convenience init(dataList: [APPSelectListAlertViewController_ItemModel],multiple_select:Bool = false) {
        self.init(groupList: [APPSelectListAlertViewController_GroupModelImpl(title: nil, items: dataList,multiple_select: multiple_select)])
    }

    public init(groupList: [APPSelectListAlertViewController_GroupModel], style: UITableView.Style = .plain) {
        self.groupList = groupList

        tableView = UITableView(frame: .zero, style: style)
        super.init(customView: tableView)

        tableView.delegate = self
        tableView.dataSource = self
    }

    public required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override public func viewDidLoad() {
        super.viewDidLoad()

        tableView.register(APPSelectListAlertCell.self, forCellReuseIdentifier: "cell")
        tableView.tableFooterView = UIView()
        tableView.separatorInset = .init(top: 0, left: 0, bottom: 0, right: 0)
        tableView.backgroundColor = style.backgroundColor
    }
    
    fileprivate var deleteCallback:DeleteCallback?
    public func setDeleteCallback(callback:@escaping DeleteCallback) {
        self.deleteCallback = callback
    }
}
public typealias DeleteCallback = ((_ alert:APPSelectListAlertViewController,_ indexPath: IndexPath,_ data:APPSelectListAlertViewController_ItemModel,_ handler: @escaping (Bool) -> Void)->())

extension APPSelectListAlertViewController: UITableViewDelegate, UITableViewDataSource {
    
    
    public func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        
        
        let data = data(indexPath)
        
        if (data.canDelete ?? false) == false {
            return nil
        }
        
        var actions = [UIContextualAction].init()
        
//        setDeleteCallback { alert, indexPath, data, handler in
//            handler(true)
//        }
        
        actions.append(UIContextualAction.init(style: UIContextualAction.Style.destructive, title: "Remove".i18n, handler: { [weak self] a, v, callback in
            
            guard let self = self else {callback(false); return }
            
            self.deleteCallback?(self,indexPath,data){ [weak self] v in
                guard let self = self else { return }
                
                if v {
                    var list = self.dataList(indexPath.section)
                    list.remove(at: indexPath.row)
                    self.groupList[indexPath.section].alert_itemModelList = list
                    self.tableView.reloadData()
                }
                
                callback(v)
            }
            
        }))
        
        let config = UISwipeActionsConfiguration.init(actions: actions)
        return config
    }
    
    public func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return groupList[section].alert_title
    }

    public func numberOfSections(in tableView: UITableView) -> Int {
        return groupList.count
    }

    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataList(section).count
    }

    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! APPSelectListAlertCell
        cell.alertViewController = self
        cell.style = self.style;
        
        let itemModel = data(indexPath)
            
        cell.model = itemModel

        configCell?(cell, itemModel)

        return cell
    }

    public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let targetV = !(data(indexPath).alert_isSelected ?? false)

        if isGlobalSingle {
            //
            let res = groupList.reduce([]) { $0 + $1.alert_itemModelList }
            res.forEach({ _, item in item.alert_isSelected = false })
        }else{
            let group = groupList[indexPath.section]
            if group.multiple_select ?? false {
                
            }else{
                let groupDataList = group.alert_itemModelList
                groupDataList.forEach({ _, item in item.alert_isSelected = false })
            }
        }
        
        data(indexPath).alert_isSelected = targetV
        tableView.reloadData()
    }
}

public class APPSelectListAlertCell: XXBaseTableViewCell<APPSelectListAlertViewController_ItemModel> {
    
    public  var style:APPAlertViewControllerStyle!{
        didSet{
            updateStyle()
        }
    }
    
    public weak var alertViewController:APPSelectListAlertViewController?
    
    
    override public func modelDidSet(oldValue: APPSelectListAlertViewController_ItemModel?, value newValue: APPSelectListAlertViewController_ItemModel?) {
        
        title_Label.text = newValue?.alert_title
        select_Button.isSelected = newValue?.alert_isSelected ?? false
        

        if newValue?.multiple_select ?? false{
            select_Button.setImage(alertViewController?.appearance.cellIcon_Multiple_UnSelect, for: .normal)
            select_Button.setImage(alertViewController?.appearance.cellIcon_Multiple_Select, for: .selected)
        }else{
            select_Button.setImage(alertViewController?.appearance.cellIcon_Single_UnSelect, for: .normal)
            select_Button.setImage(alertViewController?.appearance.cellIcon_Single_Select, for: .selected)
        }
        
    }
    
 

    override public func prepareWorkerView(workerView: UIView) {
        workerView.addSubviews([
            title_Label,
            select_Button,
        ])
        select_Button.xx_AlignInner(with: .centerRight, referView: workerView, size: CGSizeNull(), offset: .init(x: -7, y: 0))
        select_Button.snp.remakeConstraints { make in
            make.width.equalTo(18)
            make.height.equalTo(18)
        }
        title_Label.snp.remakeConstraints { make in
            make.left.equalToSuperview().offset(7)
            make.right.equalTo(select_Button.snp.left).offset(-7)
            make.centerY.equalToSuperview()
        }
    }
    func updateStyle()  {
        title_Label.textColor = style.textColor
        backgroundColor = style.backgroundColor
    }
    public lazy var title_Label = UILabel().then {
//        $0.textColor = style?.textColor
        $0.font = 15.toFont
        $0.lineBreakMode = .byTruncatingHead
    }

    public var select_Button = UIButton().then {
//        $0.setImage(#imageLiteral(resourceName: "check_unchecked").withRenderingMode(UIImage.RenderingMode.alwaysOriginal), for: .normal)
//        $0.setImage(#imageLiteral(resourceName: "check_checked").withRenderingMode(UIImage.RenderingMode.alwaysTemplate).xx.image(render: AC.mainColor), for: .selected)
        $0.isUserInteractionEnabled = false
    }
}
